/*
 * @(#) ModalShow.js
 *
 * <br> Copyright:  Copyright (c) 2017
 * <br>
 * <br> @author caijinhuang
 * <br> 2017-12-11 14:15:35
 */

import React,{Component} from 'react'
import {
    SiteHeader,
    NavItem,
    NavDropdown,
    MenuItem,
    NavSearch,
    Panel,
    Form,
    Modal,
    FormControl,
    Button,
    FormGroup,
    ControlLabel,
    Table,
    Icon,
    Tooltip,
    Overlay,
    HelpBlock,
    Glyphicon,
    InputGroup
} from '@share/shareui';
import SelectRole from "./SelectRole";
import '../../../css/modelshow.css'


/*用户注册*/
class ModalRegist extends React.Component{
    constructor(props){
        super(props);
        this.state={
            show:false,
            close:this.props.close,
            isVailable:false,
            format:false,
            oldPW:"",//旧密码
            newPW:"",//新密码
            rePW:"",//重复密码

            params:{
                username:"",//账号
                password:"",//密码
                nickname:"",//姓名
                sex:"1",//性别
                department:"",//部门
                email:"",//邮箱
                phone:""//电话号码
            },
            allDepartment:[],//部门信息
            allGroup:[]//小组信息
        }
        this.getDepartList();
    }

    /*获取部门列表*/
    getDepartList() {
        let url = "/sharemeeting/meeting/getBaseInfo.do";
        /*异步请求*/
        fetch(url, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            credentials: 'include',
            xhrFields: {
                withCredentials: true
            },
        }).then((response) => response.json()) //把response转为json
            .then((responseData) => { // 上面的转好的json
                if (responseData.status === true) {
                    console.log(responseData.data);
                    this.state.allDepartment = responseData.data.departments;
                } else {
                    alert(responseData.msg);
                }
            }).catch((error) => {
            // alert("与服务器失联了");
        })
    }

    /*用户注册*/
    userRegist(){
        let data = this.state.params;
        let isEmpty = false;
        for(let d in data){
            if(data[d]===""){
                isEmpty = true;
                break;
            }
        }
        if(!isEmpty && this.state.isVailable==="success" && this.state.format === true){
            let url = "/sharemeeting/user/regist.do";
            /*异步请求*/
            fetch(url,{
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                xhrFields: {
                    withCredentials: true
                },
                body:JSON.stringify(this.state.params)
            })
                .then((response) => response.json()) //把response转为json
                .then((responseData) => { // 上面的转好的json
                    if(responseData.status === true){
                        alert(responseData.msg);
                        for(let d in data){
                            data[d]="";
                            if(d==="sex"){
                                data[d]=1;
                            }
                        }
                        this.props.close();
                    }else{
                        alert(responseData.msg);
                    }
                }).catch((error)=> {
                alert('服务器出错了');
            })
        }else{
            if(this.state.isVailable !== "success"){
                alert("账号不可用");
            }else if(this.state.format===false){
                alert("内容格式不正确");
            }else{
                alert("信息不完整请补充完整");
            }
        }
    }

    /*账号检查*/
    checkIsVailiable(username){
        let url = "/sharemeeting/user/isAvailable.do";
        /*异步请求*/
        fetch(url,{
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            credentials: 'include',
            body:JSON.stringify({username:username})
        })
            .then((response) => response.json()) //把response转为json
            .then((responseData) => { // 上面的转好的json
                if(responseData.status === true){
                    console.log(responseData.msg);
                    this.showTooptip(false);
                    this.getValidationState("success");
                }else{
                    this.getValidationState("error");
                }
            }).catch((error)=> {
            alert('服务器出错了');
        })
    }


    getValidationState(flag){
        if(this.state.params.username.length===0){
            this.setState({isVailable:"null"});
        }else{
            this.setState({isVailable:flag});
        }
    }

    showTooptip(show){
        if(this.state.params.username.length===0){
            this.getValidationState("null");
            this.setState({show:false});
        }else{
            this.getValidationState("null");
            this.setState({show:show});
        }
    }

    render(){
        const sharedProps = {
            show: this.state.show,
            container: this,
            target:this.refs.target
        };
      return (
          <Modal show={this.props.showRegist} onHide={this.props.close} bsSize="lg">
              <Modal.Header closeButton>
                  <Modal.Title id="contained-modal-title-lg">账号注册</Modal.Title>
              </Modal.Header>
              <Modal.Body>
                  <Panel.Body full>
                      <Form pageType="addPage">
                          <Form.Table>
                              <Form.Tr>
                                  <Form.Label required>账号</Form.Label>
                                  <Form.Content colSpan="5">
                                      <FormGroup
                                          controlId="formBasicText"
                                          validationState={this.state.isVailable}>
                                          <FormControl
                                              type="text"
                                              placeholder="请输入账号"
                                              ref="target"
                                              onChange={(e)=>{
                                                  this.state.params.username = e.target.value;
                                                  /*延时加载,检查账户是否可用*/
                                                  var value = e.target.value;
                                                  if(this.clocker === null){
                                                          this.clocker = setTimeout(() => {
                                                              if((/^1[3|4|5|7|8][0-9]\d{8}$/.test(this.state.params.username))){
                                                                    this.checkIsVailiable(value)
                                                              }else{
                                                                  this.showTooptip(true);
                                                              }
                                                          }, 1000);

                                                  }else{
                                                      clearTimeout(this.clocker);//连续输入时重新计时，没有输入时，1秒后执行搜索函数。
                                                      this.clocker = setTimeout(() => {
                                                          if((/^1[3|4|5|7|8][0-9]\d{8}$/.test(this.state.params.username))){
                                                              this.checkIsVailiable(value)}
                                                          else{
                                                              this.showTooptip(true);
                                                          }
                                                      }, 1000);
                                                  }
                                              }}/>
                                          <FormControl.Feedback/>
                                          <Overlay {...sharedProps} placement="bottom">
                                              <Tooltip id="overload-left">请输入正确的手机号码</Tooltip>
                                          </Overlay>
                                      </FormGroup>
                                  </Form.Content>
                              </Form.Tr>
                              <Form.Tr>
                                  <Form.Label required>密码</Form.Label>
                                  <Form.Content colSpan="5">
                                      <FormControl type="password" placeholder="请输入密码" onChange={(e)=>{
                                          this.state.params.password = e.target.value;
                                      }}/>
                                  </Form.Content>
                              </Form.Tr>
                              <Form.Tr>
                                  <Form.Label required>性别</Form.Label>
                                  <Form.Content>
                                      <FormControl
                                          componentClass="select"
                                          onChange={(e)=>{this.state.params.sex = e.target.value}}
                                      >
                                          <option value="1">男</option>
                                          <option value="0">女</option>
                                      </FormControl>
                                  </Form.Content>
                                  <Form.Label required>部门</Form.Label>
                                  <Form.Content>
                                      <FormControl componentClass="select" onChange={(e)=>{
                                          this.state.allDepartment.forEach((value,index,array)=>{
                                              if(value.departmentId === e.target.value){
                                                  this.state.allGroup = value.groups;
                                              }
                                          })
                                          this.setState({allGroup:this.state.allGroup});}}>
                                          <option>请选择</option>{
                                          this.state.allDepartment.map(function(value,index){
                                              return (<option value={value.departmentId}>{value.departmentName}</option>);
                                          })}
                                      </FormControl>
                                  </Form.Content>
                                  <Form.Label required>小组</Form.Label>
                                  <Form.Content>
                                      <FormControl componentClass="select" onChange={(e)=>{this.state.params.department = e.target.value}}>
                                          <option>请选择</option>{
                                          this.state.allGroup.map(function(value,index){
                                              return (<option value={value.departmentInfoId}>{value.groupName}</option>);
                                          })}
                                      </FormControl>
                                  </Form.Content>
                              </Form.Tr>
                              <Form.Tr>
                                  <Form.Label required>姓名</Form.Label>
                                  <Form.Content colSpan="5">
                                      <FormControl type="text" placeholder="请输入真实姓名" onChange={(e)=>{
                                          this.state.params.nickname = e.target.value;
                                      }}/>
                                  </Form.Content>
                              </Form.Tr>
                              <Form.Tr>
                                  <Form.Label required>邮箱</Form.Label>
                                  <Form.Content colSpan="5">
                                      <FormControl type="email" placeholder="请输入邮箱账号" onChange={(e)=>{
                                          this.state.params.email = e.target.value;
                                          if((/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/).test(this.state.params.email)
                                             && (/^1[3|4|5|7|8][0-9]\d{8}$/.test(this.state.params.phone))){
                                              this.state.format = true;
                                          }else if(this.state.params.phone){
                                              this.state.format = false;
                                          }
                                      }}/>
                                  </Form.Content>
                              </Form.Tr>
                          </Form.Table>
                      </Form>
                  </Panel.Body>
              </Modal.Body>
              <Modal.Footer>
                  <Button onClick={this.props.close}>取消</Button>
                  <Button onClick={this.userRegist.bind(this)}>注册</Button>
              </Modal.Footer>
          </Modal>
      );
    };
}

/*用户管理*/
class ModalManage extends React.Component{
    constructor(props){
        super(props);
    }

    render(){
        return (
            <Modal show={this.props.showManage} onHide={this.props.close}>
                <Modal.Header closeButton>
                    <Modal.Title id="contained-modal-title-lg">用户角色管理</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <Panel.Body full>
                        <Form pageType="addPage">
                            <SelectRole />
                        </Form>
                    </Panel.Body>
                </Modal.Body>
                <Modal.Footer>
                    <Button onClick={this.props.close}>确定</Button>
                </Modal.Footer>
            </Modal>
        );
    }
}

/*用户管理*/
class ModalPassManage extends React.Component{
    constructor(props){
        super(props);
        this.state={
            username:"",//记住搜索框的内容
            userListCompnent:[]//用户列表组件数组
        }
    }

    componentWillMount(){
        this.state.userListCompnent = [];
    }

    /**
     * 用户模糊检索
     * @param username
     */
    searchUser(username){
        if(username === ""){
            this.rendUserList([]);
        }else{
            let url = "/sharemeeting/user/searchUser.do";
            /*异步请求*/
            fetch(url,{
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                body:JSON.stringify({username:username})
            })
                .then((response) => response.json()) //把response转为json
                .then((responseData) => { // 上面的转好的json
                    if(responseData.status === true){
                        this.rendUserList(responseData.data);
                    }
                }).catch((error)=> {
                alert('服务器出错了');
            })
        }
    }

    /*重置密码*/
    resetPassword(userId,event){

        event.stopPropagation();//阻止冒泡事件
        if(userId !== this.props.userInfo.userId){
            if(window.confirm("确定要重置密码吗")) {
                let url = "/sharemeeting/user/passWordReset.do";
                /*异步请求*/
                fetch(url, {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    },
                    credentials: 'include',
                    xhrFields: {
                        withCredentials: true
                    },
                    body: JSON.stringify({userId: userId})
                })
                    .then((response) => response.json()) //把response转为json
                    .then((responseData) => { // 上面的转好的json
                        if (responseData.status === true) {
                            alert(responseData.msg);
                        }else if(responseData.msg === "no login"){
                            alert("登陆失效，请重新登陆")
                            window.location.href="#/";
                        }else{
                            alert(responseData.msg);
                        }
                    }).catch((error) => {
                    // alert('服务器出错了');
                })
            }
        }
    }

    /*删除用户*/
    delUser(userId,event){
        event.stopPropagation();//阻止冒泡事件
        if(userId !== this.props.userInfo.userId){
            if(window.confirm("确定要删除该用户账号吗")) {
                let url = "/sharemeeting/user/deleteUser.do";
                /*异步请求*/
                fetch(url, {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    },
                    credentials: 'include',
                    xhrFields: {
                        withCredentials: true
                    },
                    body: JSON.stringify({userId: userId})
                })
                    .then((response) => response.json()) //把response转为json
                    .then((responseData) => { // 上面的转好的json
                        if (responseData.status === true) {
                            alert(responseData.msg);
                            this.searchUser(this.state.username);
                        }else if(responseData.msg === "no login"){
                            alert("登陆失效，请重新登陆")
                            window.location.href="#/";
                        }else{
                            alert(responseData.msg);
                        }
                    }).catch((error) => {
                    alert('服务器出错了');
                })
            }
        }
    }

    /*渲染用户列表*/
    rendUserList(data){
        this.state.userListCompnent = [];
        for(let i=0;i<data.length;i++){
            this.state.userListCompnent.push(
                <tr className="ui-del">
                    <td>{data[i].username}</td>
                    <td>{data[i].nickname}</td>
                    <td>{data[i].departmentName}</td>
                    <td>{data[i].userId !== this.props.userInfo.userId ? <div className="ui-del-meeting" onClick={this.resetPassword.bind(this,data[i].username)}><Icon className="fa fa-refresh" /></div>:null}</td>
                    <td>{data[i].userId !== this.props.userInfo.userId ? <div className="ui-del-meeting" onClick={this.delUser.bind(this,data[i].userId)}><Icon className="fa fa-remove" /></div>:null}</td>
                </tr>
            );
        }
        this.setState({userListCompnent:this.state.userListCompnent});
    }

    render(){
        return (
            <Modal show={this.props.showManage} onHide={this.props.close}>
                <Modal.Header closeButton>
                    <Modal.Title id="contained-modal-title-lg">用户管理</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <Panel.Body full>
                        <Form pageType="addPage">
                            <Form.Table>
                                <Form.Tr>
                                    {/*<Form.Label required>账号查询</Form.Label>*/}
                                    <Form.Content>
                                        <InputGroup>
                                            <InputGroup.Addon background={true}>
                                                <i className="fa fa-search"/>
                                            </InputGroup.Addon>
                                            <FormControl type="text" placeholder="用户账号" onChange={(e)=>{
                                            /*延时加载*/
                                            var value = e.target.value;
                                            this.state.username = value;
                                            if(this.clocker === null){
                                                this.clocker = setTimeout(()=>{this.searchUser(value)},1000);
                                            }else{
                                                clearTimeout(this.clocker);//连续输入时重新计时，没有输入时，1秒后执行搜索函数。
                                                this.clocker = setTimeout(()=>{this.searchUser(value)},1000);
                                            }}}/>
                                        </InputGroup>
                                    </Form.Content>
                                </Form.Tr>
                            </Form.Table>
                        </Form>
                    </Panel.Body>
                    <div className="ui-list-show">
                        <Table striped condensed hover>
                            <thead>
                                {this.state.userListCompnent.length !== 0 ? <tr><th>账号</th><th>姓名</th><th>部门</th></tr>:null}
                            </thead>
                            <tbody>
                                {this.state.userListCompnent.length !== 0 ? this.state.userListCompnent:null}
                            </tbody>
                        </Table>
                    </div>
                    <SelectRole />
                </Modal.Body>
                <Modal.Footer>
                    <Button onClick={this.props.close}>确定</Button>
                </Modal.Footer>
            </Modal>
        );
    }
}
export {ModalRegist,ModalManage,ModalPassManage}